//
//  LHStatusListViewModel.swift
//  sina_weibo
//
//  Created by 刘刘海强 on 16/5/13.
//  Copyright © 2016年 chuanzhi. All rights reserved.
//

import UIKit

class LHStatusListViewModel: NSObject {
    
    //保存微博数据
    var statusList: [LHStatusViewModel]?
    
    //获取数据
    func requestStatus(isPullUp: Bool, complete: (message: String, isSuccess: Bool)->()) {
        
        var maxId: Int64 = 0
        var sinceId: Int64 = 0
        
        if isPullUp {
            maxId = statusList?.last?.status?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        } else {
            sinceId = statusList?.first?.status?.id ?? 0
        }
        
        LHNetWorkTools.sharedTools.requestStatus((LHUserAccountModel.sharedUserAccount.userAccount?.access_token)!, maxId: maxId, sinceId:sinceId) { (response, error) -> () in
            
            var message = "没有加载到微博数据"
            
            if error != nil {
                print("网络请求异常")
                complete(message: message, isSuccess: false)
                return
            }
            
            guard let dict = response as? [String: AnyObject] else {
                print("不是一个正确的json格式")
                complete(message: message, isSuccess: false)
                return
            }
            
            //执行到此，dict是一个正常的字典
            guard let statusArray = dict["statuses"] as? [[String: AnyObject]] else {
                print("不是一个正确的json格式")
                complete(message: message, isSuccess: false)
                return
            }
            
            var tempArray = [LHStatusViewModel]()
            for value in statusArray {
                let status = LHStatus(dict: value)
                let statusViewModel = LHStatusViewModel(status: status)
                tempArray.append(statusViewModel)
            }
            
            if self.statusList == nil {
                self.statusList = [LHStatusViewModel]()
            }
            
            if isPullUp {
                self.statusList = self.statusList! + tempArray
            } else {
                self.statusList = tempArray + self.statusList!
            }
            
            let count = tempArray.count
            if count > 0 {
                message = "加载了\(count)条微博数据"
            } else {
                message = "还没有新微博"
            }

            complete(message: message, isSuccess: true)
        }
    }

}
